<template>
    <h1>excel导入<el-button @click="upFile">文件导入</el-button></h1>

    <input hidden ref="inpRef" type="file" @change="inpChange" />

    <el-table :data="tabelData" style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="brand" label="品牌" width="180" />
        <el-table-column prop="category" label="分类" width="180" />
        <el-table-column prop="desc" label="描述" />
    </el-table>
</template>

<script>
import * as XLSX from "xlsx/xlsx.mjs"
export default {
    data() {
        return {
            tabelData: []
        }
    },
    methods: {
        upFile () {
            this.$refs.inpRef.click()
        },

        inpChange(e) {
            // console.log(e.target.files);
            //获取到上传的文件
            const file = e.target.files[0]

            //创建一个文件加载器
            const reader = new FileReader()

            //指定解析/加载的文件
            reader.readAsBinaryString(file)

            const that = this
            //监听解析完毕的事件
            reader.onload = function () {
                //二进制数据流转换完毕，需要转换为认识的格式
                // console.log(reader.result)

                const box = XLSX.read(reader.result, {type: 'binary'})

                // console.log('转换完毕的数据: ', box)

                let excelInfo = box.Sheets.sheet

                excelInfo = XLSX.utils.sheet_to_json(excelInfo)

                // console.log(excelInfo);

                that.tabelData = excelInfo
            }
        }
    }
}
</script>